<template>
	<view class="commentList" style="background-color:white;width: 100%;height: auto;margin-top: 20rpx;">
		<view v-for="(l, index) in showData" :key="index" class="column"
			@longpress.stop="longpress(l.id,l.message,l.user_id)">
			<view style="display: flex;">
				<view>
					<image :src="l.img" style="width: 60rpx;height: 60rpx;border-radius: 60rpx;margin: 20rpx;"></image>
				</view>
				<view style="width: 100%;">
					<view style="display: grid;">
						<view
							style="display: flex;height: 50rpx;line-height: 50rpx;margin-top: 26rpx;justify-content: space-between;">
							<view style="display: flex;height: 30rpx;line-height: 30rpx;">
								<view class='nickName' style="font-size: 28rpx;"
									:style="l.user_id == '18' ? 'color:#ea5550':'color:#5A5A69'">
									{{l.name}}
								</view>
								<button v-show="l.user_id == '18'"
									style="padding: 2rpx 4rpx;font-size: 16rpx;margin-left: 20rpx;border-radius: 8rpx;border:1rpx solid #ea5550;background-color: #F6E4E2;color:#ea5550;">
									官方</button>
								<button v-show="l.top == '1'"
									style="padding: 2rpx 4rpx;font-size: 16rpx;margin-left: 20rpx;border-radius: 8rpx;border:1rpx solid #ea5550;background-color: #F6E4E2;color:#ea5550;">
									置顶</button>
							</view>
							<view @click.stop="toLike(l,index,r,n,'main',index)"
								style="display: grid;text-align: center;line-height: 80rpx;height: 80rpx;margin-right: 38rpx;">
								<image style="width: 34rpx;height: 34rpx;"
									:src="l.isLike == '0' ? dislikeImg : likeImg">
								</image>
								<view style="font-size: 26rpx;color: #535353;height: 26rpx;line-height: 26rpx;">
									{{l.like_num}}
								</view>
							</view>
						</view>

						<text class="content"
							style="margin-top: -10rpx;width: 530rpx;overflow-wrap: break-word;font-size: 26rpx;color: rgb(31, 138, 250)">{{extractBetweenHashes(l.message)}}</text>
						</br>
						<text class="content"
							style="margin-top: -30rpx;width: 530rpx;overflow-wrap: break-word;font-size: 26rpx;color: #000000">{{removeAfterChar(l.message)}}</text>
						<!-- 评价图片 -->
						<view style="margin-top: 10rpx;" v-if='l.dynimage && l.dynimage != ""'>
							<view style="">
								<uni-row :gutter="10" style="width: 560rpx;">
									<uni-col :span="7.5" v-for="(k,i) in l.dynimage.split(',')" :key="i">
										<image :src="k" style="width: 160rpx;height: 160rpx;" lazy-load
											@click.stop="lookBigImage(l.dynimage.split(','),i)">
										</image>
									</uni-col>
								</uni-row>
							</view>
						</view>
						<view style="display: flex;justify-content: space-between;margin-top: 14rpx;">
							<view style="display: flex;">
								<text class="time" style="font-size: 22rpx;color: #A4A4A4;">{{l.update_time}}</text>
								<button v-show="l.isLikeGuanfang != ''"
									style="padding: 2rpx 4rpx;font-size: 16rpx;margin-left: 20rpx;border-radius: 8rpx;border:1rpx solid #ea5550;background-color: #F6E4E2;color:#ea5550;">
									{{l.isLikeGuanfang}}</button>
								<button v-show="l.isCommentGuanfang != ''"
									style="padding: 2rpx 4rpx;font-size: 16rpx;margin-left: 20rpx;border-radius: 8rpx;border:1rpx solid #ea5550;background-color: #F6E4E2;color:#ea5550;">
									{{l.isCommentGuanfang}}</button>
								<text style="font-size: 22rpx;color: #616161;margin-left: 20rpx;"
									@click.stop="replyMain(l.name,l.id,l.message,l.user_id,index)">回复</text>
							</view>
						</view>

						<!-- 回复列表 -->
						<view>
							<view
								style="background-color: white;width:620rpx;height: auto;border-radius: 12rpx;margin-top: 20rpx;margin-bottom: 20rpx;">
								<view v-for="(r,n) in l.comment" :key="n" style="margin: 20rpx 20rpx 30rpx 0rpx;"
									@longpress.stop="longpress(r.id,r.message,r.user_id)"
									v-show="l.showMore == '0' ? n < 3 : n >= 0">
									<view style="display: grid;">
										<view
											style="display: flex;height: 40rpx;line-height: 40rpx;justify-content: space-between;width: 616rpx;">
											<view style="display: flex;">
												<view>
													<image :src="r.img"
														style="width: 40rpx;height: 40rpx;border-radius: 40rpx;margin-right: 10rpx;">
													</image>
												</view>
												<view
													style="display: flex;font-size: 26rpx;display: flex;height: 30rpx;line-height: 30rpx;"
													v-if="hasParent(r,l.id,l.comment) == true">
													<text class="replyname"
														:style="r.user_id == '18' || r.user_id == '67' ? 'color:#ea5550':'color:#5A5A69'">{{r.name}}</text>
													<button v-show="r.user_id == '18'" class="gfhf">
														官方</button>
													<text style="color: #5A5A69;margin-left: 20rpx;">回复
													</text>
													<text
														:style="r.replyUserId == '18' || r.user_id == '67' ? 'color:#ea5550':'color:#5A5A69'"
														style="margin-left: 20rpx;">{{hasParentName(r,l.id,l.comment)}}</text>
													<button v-show="r.replyUserId == '18'" class="gfhf">
														官方</button>
												</view>
												<view v-else style="display: flex;height: 30rpx;line-height: 30rpx;">
													<text class="replyname" style="font-size: 26rpx;margin-top: 0rpx;"
														:style="r.user_id == '18' || r.user_id == '67' ? 'color:#ea5550':'color:#5A5A69'">{{r.name}}</text>
													<button v-show="r.user_id == '18'" class="gfhf">
														官方</button>
												</view>
											</view>
											<view
												style="display: grid;line-height: 50rpx;height: 50rpx;text-align: center;margin-right: 0rpx;">
												<image style="width: 28rpx;height: 28rpx;"
													:src="r.isLike == '0' ? dislikeImg : likeImg"
													@click.stop="toLike(l,index,r,n,'list',index)">
												</image>
												<text style="font-size: 24rpx;color: #535353;">{{r.like_num}}</text>
											</view>
										</view>

										<text class="replycontent"
											style="width: 478rpx;overflow-wrap: break-word;font-size: 26rpx;margin-top: 8rpx;;margin-left: 50rpx;"
											:style="r.message == '**该条评论已被删除**' ? 'color: #999999' : 'color: #000000'">{{r.message == '**该条评论已被删除**' ? '--该条评论已被删除--' : r.message}}</text>
										<view style="margin-top: 10rpx;margin-left: 50rpx;"
											v-if='r.comment_img && r.comment_img != ""'>
											<view style="">
												<uni-row :gutter="10" style="width: 460rpx;">
													<uni-col :span="7" v-for="(kkk,iii) in r.comment_img.split(',')"
														:key="iii">
														<image :src="kkk" style="width: 120rpx;height: 120rpx;"
															lazy-load
															@click.stop="lookBigImage(r.comment_img.split(','),iii)">
														</image>
													</uni-col>
												</uni-row>
											</view>
										</view>
										<view style="display: flex;justify-content: space-between;height: 30rpx;">
											<view style="display: flex;margin-top: 16rpx;margin-left: 50rpx;">
												<text class="replytime"
													style="font-size: 22rpx;color: #A4A4A4;margin-right: 30rpx">{{r.update_time}}</text>
												<text style="font-size: 22rpx;color: #616161;"
													@click.stop="replyChild(r.name,r.id,r.message,l.id,r.user_id,index)">回复</text>
											</view>
										</view>
									</view>
								</view>

							</view>
							<view style="display: flex;height: 30rpx;line-height: 30rpx;"
								v-if="l.comment.length > 3 && l.showMore == '0'" @click="zhankai(index,l.id)">
								<view
									style="width: 30rpx;height: 0.5rpx;background-color: #AAAAAA;margin-top: 14rpx;margin-right: 10rpx;margin-left: 6rpx;">
								</view>
								<view style="font-size: 24rpx;color: #627FBA;">
									展开{{l.comment.length - 3}}条回复
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view ref="targetDom" id="yourElementId">
			<view style="background-color: transparent;width: 750rpx;position: fixed;left: 0;"
				:style="{top:0,height:clickHeight + 'px'}">
			</view>
			<view
				style="background-color: white;width: 750rpx;position: fixed;left: 0;border-top: 1rpx solid lightgray;"
				:style=" {bottom:inputBottom,height:inputHeight} ">
				<view style="display: grid;">
					<view style="display: flex;">
						<image
							style="width: 60rpx;height: 60rpx;border-radius: 60rpx;margin-left: 20rpx;margin-top: 25rpx;"
							:src="mayiicon"></image>
						<image style="width: 40rpx;height: 40rpx;margin-left: 20rpx;margin-top: 35rpx;"
							:src="writeicon">
						</image>
						<input class="uni-input myinput" cursor-spacing="0" @focus="inputBindFocus" :focus="ddfocus"
							@confirm="sendMessage()" v-model="sendValue" @blur="inputBindBlur"
							:placeholder=" sendType == 0 ? '说点什么吧' : replyName " />
						<button type="primary" @touchstart="sendMessageCustom()"
							:disabled="sendUrl == '' && sendValue == '' ? true:false "
							:style="sendUrl == '' && sendValue == '' ? 'background-color: #EC8B89' : 'background-color: #ea5550' "
							style="margin-top: 25rpx;font-size: 30rpx;margin-left: auto;margin-right:20rpx;border-radius:30rpx;color:#FFFFFF;width: 140rpx;height: 60rpx;line-height: 60rpx;">
							发送</button>
					</view>
				</view>
			</view>
		</view>
		<view style="width: 100%;height: 160rpx;background-color: white;">

		</view>
	</view>
</template>

<script>
	import {
		addPicGroupCommentLike,
		deletePicGroupCommentLike,
		addDynamicCommentLike,
		deleteDynamicCommentLike,
		addDynamicComment,
		getDynamicCommentByType,
		deleteDynamicComment
	} from '@/api/home.js';
	import {
		getCurrentBootcamp,
		getBootcampArrange
	} from '@/api/camp.js';
	import animationType from '@/utils/animationType.js';
	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from '@/libs/login.js';
	export default {
		props: {
			//数据源
			dataList: {
				type: Array,
				required: true,
				default: []
			},
			showReply: {
				type: String,
				required: true,
				default: ''
			},
			workId: {
				type: String,
				required: true,
				default: ''
			},
			receivedCommentId: {
				type: String,
				required: false,
				default: ''
			},
			userId: {
				type: String,
				required: true,
				default: ''
			},
			token: {
				type: String,
				required: true,
				default: ''
			},
		},
		data() {
			return {
				closeImg: 'https://pic.mae.vip//crmebimage/public/maintain/2024/12/12/59e7df681f374b6abfc69c17cd7082cc8rqa4xra4j.png',
				xcicon: 'https://pic.mae.vip//crmebimage/public/maintain/2024/12/12/00e42819f23845249bf91045a947f288aaje336cez.png',
				writeicon: 'https://pic.mae.vip//crmebimage/public/maintain/2024/08/07/7a43c3c33bbc49279c0463cf88d5fb7329vlfes1mr.png',
				mayiicon: 'http://pic.mae.vip/5d44b9908d6757e2df2da81708927763023',
				loading: false,
				inputBottom: 0,
				likeImg: 'https://pic.mae.vip//crmebimage/public/maintain/2024/12/12/ba1b55bb9c494796b8082a8253be25d7u6uvdtz1zy.png',
				dislikeImg: 'https://pic.mae.vip//crmebimage/public/maintain/2024/12/12/a59744f5dc2449e985e54bea77780d8257xjdp2y87.png',
				sendValue: '',
				replyType: 'main',
				replyName: '',
				ddfocus: false,
				parentId: -1,
				rootId: -1,
				showData: [],
				screenHeight: 0,
				clickHeight: 0,
				sendUrl: '',
				inputHeight: 0,
				sendType: 0,
				zhankaiArr: [],
				noticeUserId: '', //通知用户userid
				replyRootId: 0,
				replyIndex: 0,
				keyboardHeight: 0,
				initialHeight: window.innerHeight,
				screenHeight: uni.getSystemInfoSync().screenHeight,
			};
		},
		computed: mapGetters(['isLogin', 'uid', 'userInfo', 'md5AppToken', 'appUserId']),
		watch: {
			dataList: {
				immediate: true,
				deep: true,
				handler(newValue, oldValue) {
					this.$nextTick(() => {
						if (newValue) {
							this.showData = [];
							this.showData = newValue;
						}
					})
				},
			},
			ddfocus: {
				handler(newValue, oldValue) {
					console.log('****' + newValue)
					if (newValue == true) {
						this.$emit('hideFun', false);
					} else {
						this.$emit('hideFun', true);
					}
				},
			},
		},
		mounted() {
			let that = this;
			document.querySelector('meta[name="viewport"]').setAttribute('content',
				'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');

			document.addEventListener('ddfocus', function(event) {
				if (['INPUT', 'TEXTAREA'].includes(event.target.tagName)) {
					// 增加少量延迟，确保键盘已弹出或正在弹出
					setTimeout(() => {
						event.target.scrollIntoView({
							behavior: 'smooth',
							block: 'center' // 或 'start', 'nearest'
						});
					}, 300); // 延迟时间可根据实际情况调整
				}
			}, true); // 使用捕获模式



			// （可选）监听输入框的 focus，用于更精确触发
			const input = document.querySelector('input');
			input.addEventListener('focus', () => {
				setTimeout(() => {
					const currentHeight = window.innerHeight;
					const diff = that.initialHeight - currentHeight;



					const query = uni.createSelectorQuery()
						.select('#yourElementId') // 选择器，比如 ID 选择器
						.boundingClientRect((rect) => {
							console.log('元素位置信息：', rect.top);
							// rect 包含 top, left, width, height 等
							that.inputBottom = 0 + 'px';
						})
						.exec(); // 必须调用 exec() 才会执行查询


					if (that.sendType == 2) {
						that.inputHeight = 60 + 'px';
						that.clickHeight = that.screenHeight - diff - 60;
					} else {
						if (that.sendUrl == '') {
							that.inputHeight = 60 + 'px';
							that.clickHeight = that.screenHeight - diff - 60;
						} else {
							that.inputHeight = 110 + 'px';
							that.clickHeight = that.screenHeight - diff - 110;
						}
					}
				}, 300); // 延迟确保键盘渲染完成
			});

			input.addEventListener('blur', () => {
				setTimeout(() => {
					that.inputBottom = 0;
					that.inputHeight = 0;
					that.clickHeight = 0;
				}, 300);
			});
		},
		methods: {
			extractBetweenHashes(str) {
				// 使用正则表达式匹配第一个#和第二个#之间的内容，包括#
				const regex = /(#.*?#)/;
				const match = str.match(regex);
				// 如果匹配成功，返回匹配到的整个字符串；否则返回空字符串
				return match ? match[0] : "";
			},
			removeAfterChar(str) {
				const parts = str.split('#');
				if (parts.length > 2) {
					return parts[2]; // 返回第二个#之后的内容，即parts[2]
				}
				return str; // 如果没有足够的#，返回空字符串
			},
			changeFocus() {
				let that = this;
				uni.pageScrollTo({
					scrollTop: 100000, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
					duration: 1 // 滚动动画时长
				});


				that.$nextTick(() => {
					that.ddfocus = true;
					that.sendType = 0;
					document.querySelector('input').focus();
				});
			},
			inputBindFocus(e) {
				let that = this;
				uni.pageScrollTo({
					scrollTop: 100000, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
					duration: 1 // 滚动动画时长
				});
			},
			inputBindBlur(e) {
				let that = this;
				that.ddfocus = false;
				that.replyType = 'main';
				that.inputBottom = 0;
				that.clickHeight = 0;
				that.inputHeight = 0;
				// setTimeout(() => {
				// 	//that.inputBottom = 0;
				// }, 1)
			},
			uploadpic: function() {
				let that = this;
				that.$util.uploadImageOne({
					url: 'user/upload/image',
					name: 'multipart',
					model: "product",
					pid: 1
				}, function(res) {
					that.sendUrl = res.data.url;
					// uni.pageScrollTo({
					// 	scrollTop: 0, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
					// 	duration: 1 // 滚动动画时长
					// });
					that.ddfocus = true;
					// setTimeout(() => {
					// 	that.ddfocus = true;
					// }, 500)

					//console.log('!@#---' + JSON.stringify(res))
					//that.pics.push(res.data.url);
					//that.picsPath.push(res.data.localPath);
				});
			},
			zhankai(index, id) {
				let that = this;
				that.showData[index].showMore = '1';

				let dic = {
					'showMore': '1',
					'id': id
				}
				that.zhankaiArr.push(dic);
			},
			replyChild(name, id, message, rootid, userid, index) {
				let that = this;
				that.replyRootId = rootid;
				that.replyIndex = index;
				// if (that.md5AppToken == -1) {
				// 	//去登录
				// 	toLogin();
				// }
				// if (message == '**该条评论已被删除**') {
				// 	return;
				// }

				that.sendType = 2;
				that.replyType = 'list';
				that.replyName = '回复@' + name;
				that.parentId = id;
				that.rootId = rootid;

				// uni.pageScrollTo({
				// 	scrollTop: 0, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
				// 	duration: 1 // 滚动动画时长
				// });

				that.ddfocus = true;
				// setTimeout(() => {
				// 	that.ddfocus = true;
				// }, 100)

				that.noticeUserId = userid;
			},
			replyMain(name, id, message, userid, index) {
				let that = this;
				that.replyRootId = id;
				that.replyIndex = index;
				// if (that.md5AppToken == -1) {
				// 	//去登录
				// 	toLogin();
				// }
				// if (message == '**该条评论已被删除**') {
				// 	return;
				// }

				that.sendType = 1;
				that.replyType = 'main';
				that.replyName = '回复@' + name;
				that.parentId = id;
				that.rootId = id;

				// uni.pageScrollTo({
				// 	scrollTop: 0, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
				// 	duration: 1 // 滚动动画时长
				// });
				that.ddfocus = true;
				// setTimeout(() => {
				// 	that.ddfocus = true;
				// }, 100)

				that.noticeUserId = userid;
			},
			sendMessageCustom() {
				let that = this;
				console.log('55555');
				if (that.sendUrl == '' && that.sendValue == '') {
					return;
				}
				that.sendMessage();
			},
			sendMessage() {
				console.log('!@#---666777')
				//return;
				let that = this;

				let params = {};
				params.token = that.token;
				params.userId = that.userId;
				params.device = '1';
				params.message = that.sendValue;
				params.dynId = that.workId; //照片 id
				// if (that.replyType == 'list') {
				// 	params.parentId = that.parentId; //评价父id 一级评论为0
				// } else {
				// 	params.parentId = that.receivedCommentId; //评价父id 一级评论为0
				// }
				// params.rootId = that.receivedCommentId; //根评论id,一级评论为0

				if (that.sendType == 0) { //评论用户案例
					params.parentId = 0;
					params.rootId = 0;
				}
				if (that.sendType == 1) { //回复一级评论
					params.parentId = that.parentId;
					params.rootId = that.rootId;
				}
				if (that.sendType == 2) { //回复二级评论
					params.parentId = that.parentId;
					params.rootId = that.rootId;
				}
				params.image = that.sendUrl;
				params.type = "用户案例";
				params.noticeUserId = that.sendType == 0 ? '0' : that.noticeUserId; //通知用户id
				console.log('---------111   ' + JSON.stringify(params))
				//return;
				addDynamicComment(params).then(res => {
					that.sendValue = '';
					that.sendUrl = '';
					that.sendType = 0;
					that.getComment();
					uni.showToast({
						title: res.msg
					})

				})
			},
			getComment() {
				let that = this;
				that.$emit('refreshSingleReply', {
					'rootId': that.replyRootId,
					'replyIndex': that.replyIndex
				});
			},
			toLike(l, i, r, n, type, index) {
				let that = this;
				that.replyRootId = l.id;
				that.replyIndex = index;
				if (type == 'main') {
					if (l.isLike == '0') {
						addPicGroupCommentLike({
							commentId: l.id,
							noticeUserId: l.user_id,
							token: that.token,
							userId: that.userId,
						}).then(res => {
							//that.showData[i].isLike = '1';
							//that.showData[i].like_num++;
							that.$emit('refreshSingleReply', {
								'rootId': that.replyRootId,
								'replyIndex': that.replyIndex
							});
						})
					} else {
						deletePicGroupCommentLike({
							commentId: l.id,
							token: that.token,
							userId: that.userId,
						}).then(res => {
							// that.showData[i].isLike = '0';
							// if (that.showData[i].like_num > 0) {
							// 	that.showData[i].like_num--;
							// }
							that.$emit('refreshSingleReply', {
								'rootId': that.replyRootId,
								'replyIndex': that.replyIndex
							});
						})
					}
				} else {
					if (r.isLike == '0') {
						addDynamicCommentLike({
							commentId: r.id,
							noticeUserId: r.user_id,
							token: that.token,
							userId: that.userId,
						}).then(res => {
							//that.showData[i].comment[n].isLike = '1';
							//that.showData[i].comment[n].like_num++;
							that.$emit('refreshSingleReply', {
								'rootId': that.replyRootId,
								'replyIndex': that.replyIndex
							});
						})
					} else {
						deleteDynamicCommentLike({
							commentId: r.id,
							token: that.token,
							userId: that.userId,
						}).then(res => {
							// that.showData[i].comment[n].isLike = '0';
							// if (that.showData[i].comment[n].like_num > 0) {
							// 	that.showData[i].comment[n].like_num--;
							// }
							that.$emit('refreshSingleReply', {
								'rootId': that.replyRootId,
								'replyIndex': that.replyIndex
							});

						})
					}
				}


			},
			hasParent(r, commentId, comment) {
				let has = false;
				for (let i = 0; i < comment.length; i++) {
					if (r.parent_id == comment[i].parent_id && r.parent_id != commentId) {
						has = true;
					}
				}
				return has;
			},
			hasParentName(r, commentId, comment) {
				let name = '';
				for (let i = 0; i < comment.length; i++) {
					if (r.parent_id == comment[i].parent_id && r.parent_id != commentId) {
						name = comment[i].replyName;
					}
				}
				return name;
			},
			lookImage(url) {
				return;
				uni.previewImage({
					urls: url.split(","),
					current: 0
				});
			},
			lookBigImage(arr, index) {
				uni.previewImage({
					urls: arr,
					current: index
				});
			},
		},
	};
</script>

<style scoped>
	.myinput {
		background: white;
		height: 70rpx;
		margin-top: 20rpx;
		margin-left: 20rpx;
		width: 400rpx;
		font-size: 28rpx;
	}

	.gfhf {
		padding: 2rpx 4rpx;
		font-size: 16rpx;
		margin-left: 20rpx;
		border-radius: 8rpx;
		border: 1rpx solid #ea5550;
		background-color: #F6E4E2;
		color: #ea5550;
	}
</style>